package com.COMP3111H.project;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class My_Profile_Account extends Activity implements OnClickListener {
	TextView creditInfo;
	Button confirmUpdate, changePwd;
	TextView dateCreatedUI;
	TextView currentCreditUI;
	EditText nicknameUI;
	EditText firstnameUI;
	EditText lastnameUI;
	EditText phoneUI;
	String username;
	ProgressThread progThread;
	final int SPINNER = 0;
	ProgressDialog progDialog;

	final int CHANGE_PWD = 1;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.my_profile_account);
		
		String[] usernamePassword = LoginUtility.getUsernamePassword(My_Profile_Account.this);
		username = usernamePassword[0];
		
		nicknameUI = (EditText) findViewById(R.id.et_MyProfile_Account_Nickname);
		firstnameUI = (EditText) findViewById(R.id.et_MyProfile_Account_Firstname);
		lastnameUI = (EditText) findViewById(R.id.EditText01);
		phoneUI = (EditText) findViewById(R.id.EditText02);
		dateCreatedUI = (TextView) findViewById(R.id.tv_MyProfile_Account_DateCreate);
		currentCreditUI = (TextView) findViewById(R.id.tv_MyProfile_Account_Credit);
		
		showDialog(SPINNER);
		progThread = new ProgressThread(mhandler, 0);
		progThread.start();
		
		(creditInfo = (TextView) findViewById(R.id.tv_MyProfile_Account_Whatisthis))
				.setOnClickListener(this);

		(confirmUpdate = (Button) findViewById(R.id.b_MyProfile_Account_Confirm))
		.setOnClickListener(this);
		
		(changePwd = (Button) findViewById(R.id.b_MyProfile_Account_ChangePassword))
		.setOnClickListener(this);
	}

	public void onClick(View v) {
		Intent myIntent;
		switch (v.getId()) {
		
		case R.id.tv_MyProfile_Account_Whatisthis:
			myIntent = new Intent(this, More_InfoCredit.class);
			startActivity(myIntent);
			break;
			
		case R.id.b_MyProfile_Account_Confirm:
			String nickname = nicknameUI.getText().toString();
			String firstname = firstnameUI.getText().toString();
			String lastname = lastnameUI.getText().toString();
			String phone = phoneUI.getText().toString();
			
			if(!NetworkUtility.inputCheck(nickname) || !NetworkUtility.inputCheck(firstname) || 
					!NetworkUtility.inputCheck(lastname) || !NetworkUtility.inputCheck(phone))
					Toast.makeText(My_Profile_Account.this,"There are special characters that are not allowed in your request", Toast.LENGTH_SHORT).show();
			else{
				if(phone.matches("")){
					Toast.makeText(
							My_Profile_Account.this,
							"Phone number cannot be empty.",
							Toast.LENGTH_SHORT).show();
					return;
				}
				showDialog(SPINNER);
				progThread = new ProgressThread(mhandler, 1);
				progThread.start();
			}
			break;
			
		case R.id.b_MyProfile_Account_ChangePassword:
			
			myIntent = new Intent(this, My_Profile_Account_ChangePwd.class);
			//startActivityForResult(myIntent, CHANGE_PWD);
			startActivity(myIntent);
			break;
		}
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case 0: // Spinner
			progDialog = new ProgressDialog(this);
			progDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			progDialog.setMessage("Loading...");

			return progDialog;
		default:
			return null;
		}
	}

	// Handler on the main (UI) thread that will receive messages from the
	// second thread and update the progress.

	final Handler mhandler = new Handler() {
		public void handleMessage(Message msg) {
			// Get the current value of the variable total from the message data
			// and update the progress bar.
			String returnedData = msg.getData().getString("returnedData");
			removeDialog(SPINNER);		
			int from = msg.getData().getInt("from");
			if(from == 0){
				if(!returnedData.contains("error")){
					try {
						JSONObject info = new JSONObject(returnedData);
						String PhoneNumber = info.getString("PhoneNumber");
						String NickName = info.getString("NickName");
						String FirstName = info.getString("FirstName");
						String LastName = info.getString("LastName");
						String DateCreated = info.getString("DateCreated");
						String Credit = info.getString("Credit");
						if(!PhoneNumber.matches("N/A") && PhoneNumber!= null)
							phoneUI.setText(PhoneNumber);
						if(!NickName.matches("N/A") && NickName!= null)
							nicknameUI.setText(NickName);
						if(!FirstName.matches("N/A") && FirstName != null)
							firstnameUI.setText(FirstName);
						if(!LastName.matches("N/A") && LastName != null)
							lastnameUI.setText(LastName);
						
						dateCreatedUI.setText(DateCreated);
						currentCreditUI.setText(Credit);
					} catch (JSONException e) {
						throw new RuntimeException(e);
					}
				}
				else{
					Toast.makeText(
							My_Profile_Account.this,
							"Network Error",
							Toast.LENGTH_SHORT).show();
				}
			}
			else if(from == 1){
				if(returnedData.contains("update_account_info_successful"))
					Toast.makeText(
							My_Profile_Account.this,
							"Account Updated",
							Toast.LENGTH_SHORT).show();
				else if(returnedData.contains("update_account_info_failed"))
					Toast.makeText(
							My_Profile_Account.this,
							"Update Failed",
							Toast.LENGTH_SHORT).show();
				else
					Toast.makeText(
							My_Profile_Account.this,
							"Network Error",
							Toast.LENGTH_SHORT).show();
				}
		}
	};

	private class ProgressThread extends Thread {
		// Class constants defining state of the thread
		Handler mHandler;
		int from;

		ProgressThread(Handler h, int f) {
			mHandler = h;
			from = f;
		}

		@Override
		public void run() {
			Message msg = mHandler.obtainMessage();
			if(from == 0){
				List<NameValuePair> params = new ArrayList<NameValuePair>(1);
				params.add(new BasicNameValuePair("username", username));
				String returnedData = NetworkUtility.sendHTTP(params,"http://webproject2.cse.ust.hk:8029/BookwarmMobile/jsp/account_info_display.jsp");
				Bundle b = new Bundle();
				b.putString("returnedData", returnedData);
				b.putInt("from", from);
				msg.setData(b);
				mHandler.sendMessage(msg);
			}
			else if(from == 1){
				String nickname = nicknameUI.getText().toString();
				String firstname = firstnameUI.getText().toString();
				String lastname = lastnameUI.getText().toString();
				String phone = phoneUI.getText().toString();
				Log.v("Bookwarm", nickname + "," + firstname + "," + lastname + "," + phone);
				List<NameValuePair> params = new ArrayList<NameValuePair>(5);
				params.add(new BasicNameValuePair("username", username));
				params.add(new BasicNameValuePair("nickname", nickname));
				params.add(new BasicNameValuePair("firstname", firstname));
				params.add(new BasicNameValuePair("lastname", lastname));
				params.add(new BasicNameValuePair("phonenumber", phone));
				String returnedData = NetworkUtility.sendHTTP(params,"http://webproject2.cse.ust.hk:8029/BookwarmMobile/jsp/account_info_update.jsp");
				Bundle b = new Bundle();
				b.putString("returnedData", returnedData);
				b.putInt("from", from);
				msg.setData(b);
				mHandler.sendMessage(msg);
			}
		}

		// Set current state of thread (use state=ProgressThread.DONE to stop
		// thread)

	}
}
